<?php

namespace backend\controllers;

use Yii;
use backend\models\PrfConfig;
use backend\models\PrfConfigSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;
use backend\models\GrpPriceEx;
use backend\models\GrpItemEx;
use backend\models\GrpBrand;
use backend\models\SysItem;

/**
 * PrfConfigController implements the CRUD actions for PrfConfig model.
 */
class PrfConfigController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    
    
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('config-manage')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all PrfConfig models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PrfConfigSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single PrfConfig model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new PrfConfig model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PrfConfig();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing PrfConfig model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
        	date_default_timezone_set('Asia/Shanghai');
        	$model->updatetime = date('Y-m-d H:i:s',time());
        	$model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing PrfConfig model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PrfConfig model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PrfConfig the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PrfConfig::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * 动态新增价格扩展
     * @return Ambigous <string, string>
     */
    public function actionPriceEx()
    {
    	//$this->layout = 'main_small';
    	return $this->render('price_ex');
    }
    public function actionAddPriceEx($name)
    {
    	$model = new GrpPriceEx();
    	$model->name = $name;
    	if($model->save())
    	{
    		$_arr = array('id'=>$model->id,'name'=>$model->name);
    		echo json_encode($_arr);
    	}
    }
    public function actionSetCookiesForPriceEx($id,$name)
    {
    
    
    	$cookies_set = Yii::$app->response->cookies;
    	$cookies_get = Yii::$app->request->cookies;
    	//	unset($cookies_set['price_ex']);
    	//var_dump($cookies_get['price_ex']);
    
    	if (isset($cookies_get['price_ex'])) {
    		$price_ex = $cookies_get['price_ex']->value;
    		array_push($price_ex, [$id,$name]);
    		unset($cookies_set['price_ex']);
    		$cookies_set->add(new \yii\web\Cookie([
    				'name' => 'price_ex',
    				'value' => $price_ex,
    				]));
    		var_dump($cookies_get['price_ex']);
    	}
    	else {
    		$cookies_set->add(new \yii\web\Cookie([
    				'name' => 'price_ex',
    				'value' => [[$id,$name]],
    				]));
    		var_dump($cookies_get['price_ex']);
    	}
    
    }
    
    public function actionItemEx()
    {
    	//$this->layout = 'main_small';
    	return $this->render('item_ex');
    }
    public function actionAddItemEx($name)
    {
    	$model = new GrpItemEx();
    	$model->name = $name;
    	if($model->save())
    	{
    		$_arr = array('id'=>$model->id,'name'=>$model->name);
    		echo json_encode($_arr);
    	}
    }
    
    /**
     * 批量设置折扣价
     * @param unknown $head_grp
     */
    public function actionSelectBrand($head_grp){
    	$model = GrpBrand::findAll(['head_grp'=>$head_grp]);
    	$selece_brand ='';
    	foreach ($model as $value){
    		$selece_brand .= '<label id="'.$value['id'].'"><input name="SysItem[brand_id_for_price][]" value="'.$value['id'].'" type="checkbox" ></input>'.$value['name'].'</label>';
    	}
    	echo $selece_brand;
    	 
    }
    public function actionDeleteBrand($head_grp){
    	$model = GrpBrand::findAll(['head_grp'=>$head_grp]);
    	$arr = array();
    	foreach ($model as $value)
    	{
    		array_push($arr, $value['id']);
    	}
    	//var_dump($arr);
    	return json_encode($arr);
    }
    /*设置全部的折扣价*/
    public function actionSetDiscountPriceBatch()
    {
    	$class_select = '';
    	$model = new SysItem();
    	if ($model->load(Yii::$app->request->post())) {
    
    		if(!empty($model->class_id)){$class_select = $model->class_id;}
    		else if(!empty($model->class2)){$class_select = $model->class2;}
    		else if(!empty($model->class1)){$class_select = $model->class1;}
    		 
    		if($model->price_batch_all == 1){//全选
    			SysItem::updateAll(['price_discount'=>$model->price_batch],'');
    		}elseif($class_select!=0){//类别
    			SysItem::updateAll(['price_discount'=>$model->price_batch],'class_id='.$class_select);
    		}elseif(!empty($model->brand_id_for_price)){//单个品牌
    			 
    			foreach ($model->brand_id_for_price as $value){
    				SysItem::updateAll(['price_discount'=>$model->price_batch],'brand_id='.$value);
    			}
    		}
    		echo '<script>alert("折扣价批量设置成功");</script>';
    		return $this->redirect(['sys-item/index']);
    
    		 
    	} else {
    		return $this->render('set_discount_price_batch', [
    				'model' => $model,
    				]);
    	}
    }
}
